package com.peycard.persistence.dao;

import java.io.Serializable;
import java.lang.reflect.ParameterizedType;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import com.peycard.common.util.Constantes;
import com.peycard.persistence.PersistenceException;
import com.peycard.persistence.dao.local.GenericDAO;

public class GenericDAOImpl<T, PK extends Serializable> implements
		GenericDAO<T, PK> {
	protected Class<T> entityClass;

	@PersistenceContext
	protected EntityManager entityManager;

	public GenericDAOImpl() {
		ParameterizedType genericSuperclass = (ParameterizedType) getClass()
				.getGenericSuperclass();
		this.entityClass = (Class<T>) genericSuperclass
				.getActualTypeArguments()[0];
	}

	@Override
	public T create(T t) throws PersistenceException {
		try {
			this.entityManager.persist(t);
			return t;
		} catch (Exception ex) {
			throw new PersistenceException(
					Constantes.ERROR_GENERICO_PERSISTENCIA, ex);
		}

	}

	@Override
	public T read(PK id) throws PersistenceException {
		try {
			return this.entityManager.find(entityClass, id);
		} catch (Exception ex) {
			throw new PersistenceException(
					Constantes.ERROR_GENERICO_PERSISTENCIA, ex);
		}

	}

	@Override
	public T update(T t) throws PersistenceException {
		try {
			return this.entityManager.merge(t);
		} catch (Exception ex) {
			throw new PersistenceException(
					Constantes.ERROR_GENERICO_PERSISTENCIA, ex);
		}

	}

	@Override
	public void delete(T t) throws PersistenceException {
		try {
			t = this.entityManager.merge(t);
			this.entityManager.remove(t);
		} catch (Exception ex) {
			throw new PersistenceException(
					Constantes.ERROR_GENERICO_PERSISTENCIA, ex);
		}

	}

	public EntityManager getEntityManager(){
		return this.entityManager;
	}
	
}
